<template>
  <div class="cart">
    <order-header title="我的购物车">
      <template v-slot:tip>
        <span>温馨提示：产品是否购买成功，以最终下单为准哦，请尽快结算</span>
      </template>
    </order-header>
    <div class="wrapper">
      <div class="container">
        <div class="cart-box">
          <ul class="cart-item-head">
            <li class="col-1"><span class="checkbox" v-bind:class="{'checked': checkAll}" @click="allCheck"></span>全选</li>
            <li class="col-3">商品</li>
            <li class="col-1">单价</li>
            <li class="col-2">数量</li>
            <li class="col-1">小计</li>
            <li class="col-1">操作</li>
          </ul>
          <ul class="cart-item-list">
            <li class="cart-item" v-for="(item, index) in list" v-bind:key="index">
              <div class="item-check">
                <span class="checkbox" @click="checkItem(item.cartItemId)" v-bind:class="{'checked': result.includes(item.cartItemId)}"></span>
              </div>
              <div class="item-name">
                <img v-lazy="item.goodsCoverImg" alt="">
                <span>{{item.goodsName}}</span>
              </div>
              <div class="item-price">{{item.sellingPrice}}</div>
              <div class="item-num">
                <div class="num-box">
                  <a href="javascript:;" @click="reduceNum(item.cartItemId, item.goodsCount)">-</a>
                  <span >{{item.goodsCount}}</span>
                  <a href="javascript:;" @click="addNumber(item.cartItemId, item.goodsCount)">+</a>
                </div>
              </div>
              <div class="item-total">{{item.goodsCount * item.sellingPrice}}</div>
              <div class="item-del" @click="deleteGood(item.cartItemId)"></div>
            </li>
          </ul>
        </div>
        <div class="order-wrap clearfix">
          <div class="cart-tip fl">
            <a href="/index">继续购物</a>
            共<span>{{list.length}}</span>件商品，已选择<span>{{result.length}}</span>件，总价<span>{{total}}</span>
          </div>
          <div class="total fr">
            <a href="javascript:;" class="btn" @click="order" style="background-color: #1baeae;">去结算</a>
          </div>
        </div>
      </div>
    </div>
    <service-bar></service-bar>
    <nav-footer></nav-footer>
    <el-dialog title="选择收货地址" :visible.sync="dialogTableVisible">
      <el-table :data="addressList">
        <el-table-column prop="userName" label="收货人"></el-table-column>
        <el-table-column prop="userPhone" label="收货电话"></el-table-column>
        <el-table-column prop="provinceName" label="省份"></el-table-column>
        <el-table-column prop="cityName" label="城市"></el-table-column>
        <el-table-column prop="regionName" label="区县"></el-table-column>
        <el-table-column prop="detailAddress" label="详细地址"></el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button @click="selectAddress(scope.row.addressId)" type="text">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script>
import OrderHeader from './../components/OrderHeader'
import ServiceBar from './../components/ServiceBar'
import NavFooter from './../components/NavFooter'
import { getCart, deleteCartItem, modifyCart } from '../service/cart'
import { getAddressList } from '../service/address'

export default{
  name: 'index',
  components: {
    OrderHeader,
    ServiceBar,
    NavFooter
  },
  data() {
    return {
      checkedNum: 0,//选中商品数量
      checked: false,
      list: [],
      all: false,
      result: [],
      checkAll: true,
      dialogTableVisible: false,
      addressList: []
    }
  }, 
  computed: {
    total() {
      let sum = 0
      let _list = this.list.filter(item => this.result.includes(item.cartItemId))
      _list.forEach(item => {
        sum += item.goodsCount * item.sellingPrice
      })
      return sum
    }
  },
  mounted() {
    // 获取数据
    this.init()
  },
  methods:{
    async init() {
      // loading
      const { data } = await getCart({ pageNumber: 1 })
      this.list = data
      this.result = data.map(item => item.cartItemId)
    },
    async reduceNum(id, num) {
      if(num === 1) {
        return this.$message.error('商品数量不能小于1')
      }
      const params = {
        cartItemId: id,
        goodsCount: num - 1
      }
      const { data } = await modifyCart(params)
      this.list.forEach(item => {
        if (item.cartItemId == id) {
          item.goodsCount = num - 1
        }
      })
    },
    async addNumber(id, num) {
      const params = {
        cartItemId: id,
        goodsCount: num + 1
      }
      const { data } = await modifyCart(params)
      this.list.forEach(item => {
        if (item.cartItemId == id) {
          item.goodsCount = num + 1
        }
      })
    },
    // 购物车下单
    async order() {
      if (this.result.length == 0) {
        return this.$message.error('请选择商品进行结算')
      }
      const res = await getAddressList()
      this.addressList = res.data
      this.dialogTableVisible = true
    },
    selectAddress(addressId) {
      this.dialogTableVisible = false
      const params = JSON.stringify(this.result)
      localStorage.setItem('cartItemIds', params)
      localStorage.setItem('addreddId', addressId)
      this.$router.push({ path: `create-order?addressId=${addressId}&cartItemIds=${params}` })
    },
    async deleteGood(id) {
      await deleteCartItem(id)
      this.$message.success('删除购物车成功！')
      this.init()
    },
    allCheck() {
      if (!this.checkAll) {
        this.checkAll = true
        this.result = this.list.map(item => item.cartItemId)
      } else {
        this.checkAll = false
        this.result = []
      }
    },
    checkItem(id) {
      if(this.result.includes(id)) {
        this.result = this.result.filter(item => item != id)
      } else {
        this.result.push(id)
      }
    }
  },
}
</script>
<style lang="less" scoped>
  .cart{
    .wrapper{
      background-color:#F5F5F5;
      padding-top:30px;
      padding-bottom:114px;
      .cart-box{
        background-color:#fff;
        font-size:14px;
        color:#999999;
        text-align:center;
        .checkbox{
          display: inline-block;
          width: 22px;
          height: 22px;
          border: 1px solid #E5E5E5;
          vertical-align: middle;
          margin-right: 17px;
          cursor:pointer;
          &.checked{
            background:url('/imgs/icon-gou.png') #1baeae no-repeat center;
            background-size:16px 12px;
            border:none;
          }
        }
        .cart-item-head{
          display:flex;
          height: 79px;
          line-height: 79px;
          .col-1{
            flex:1;
          }
          .col-2{
            flex:2;
          }
          .col-3{
            flex:3;
          }
        }
        .cart-item-list{
          .cart-item{
            display:flex;
            align-items:center;
            height:125px;
            border-top:1px solid #E5E5E5;
            font-size:16px;
            .item-check{
              flex:1;
            }
            .item-name{
              flex:3;
              font-size: 18px;
              color: #333333;
              display: flex;
              align-items: center;
              img{
                width:80px;
                height:80px;
                vertical-align:middle;
              }
              span{
                margin-left: 30px;
              }
            }
            .item-price{
              flex:1;
              color:#333333;
            }
            .item-num{
              flex:2;
              .num-box{
                display:inline-block;
                width:150px;
                height:40px;
                line-height:40px;
                border:1px solid #E5E5E5;
                font-size:14px;
                a{
                  display:inline-block;
                  width:50px;
                  color:#333333;
                }
                span{
                  display:inline-block;
                  width:50px;
                  color:#333333;
                }
              }
            }
            .item-total{
              flex:1;
              color:#1baeae;
            }
            .item-del{
              flex:1;
              width:14px;
              height:12px;
              background:url('/imgs/icon-close.png') no-repeat center;
              background-size:contain;
              cursor:pointer;
            }
          }
        }
      }
      .order-wrap{
        font-size:14px;
        color: #666666;
        margin-top: 20px;
        height: 50px;
        line-height: 50px;
        .cart-tip{
          margin-left: 29px;
          a{
            color: #666666;
            margin-right:37px;
          }
          span{
            color:#1baeae;
            margin:0 5px;
          }
        }
        .total{
          font-size:14px;
          color:#1baeae;
          span{
            font-size:24px;
          }
          a{
            width:202px;
            height:50px;
            line-height:50px;
            font-size:18px;
            margin-left:37px;
          }
        }
      }
    }
  }
</style>